<?php 

	session_start();

	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {

		// no login, move to index page
		header("Location: http://localhost/atbat/html/");

	}

	// connect to db
	require_once '../db/db.php';

	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";

	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];

	// create player
	if(isset($_POST['create_player'])) {

		$error = false;
		$options = array('min_range' => 0, 'max_range' => 99);

		// validate and sanitize data
		if(isset($_POST['first_name']) && $_POST['first_name'] != '') {

			$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);

		}else{

			$message[] = '<p class="error">Please give your player a first name.</p>';
			$error = true;

		}

		if(isset($_POST['last_name']) && $_POST['last_name'] != '') {

			$last_name = filter_var($_POST['last_name'], FILTER_SANITIZE_STRING);

		}else{

			$message[] = '<p class="error">Please give your player a last name.</p>';
			$error = true;

		}

		$name = $first_name . ' ' . $last_name;

		if(isset($_POST['number']) && $_POST['number'] != '') {

			if(filter_var($_POST['number'], FILTER_VALIDATE_INT, $options)) {

				$number = filter_var($_POST['number'], FILTER_SANITIZE_NUMBER_INT);

			}else{

				$message[] = '<p class="error">Player number must be a number between 0 &amp; 99.</p>';
				$error = true;

			}

		}else{

			$message[] = '<p class="error">Please give your player a number.</p>';
			$error = true;

		}

		if(isset($_POST['position']) && $_POST['position'] != '') {

			$options = array('min_range' => 0, 'max_range' => 9);
			if(filter_var($_POST['position'], FILTER_VALIDATE_INT, $options)) {

				$position = filter_var($_POST['position'], FILTER_SANITIZE_NUMBER_INT);

			}else{

				$message[] = '<p class="error">Please choose a postion from the list.</p>';
				$error = true;

			}

		}else{

			$message[] = '<p class="error">Please choose a position for your player.</p>';
			$error = true;

		}

		if(isset($_POST['bats']) && $_POST['bats'] != '') {

			$bats = filter_var($_POST['bats'], FILTER_SANITIZE_STRING);

		}else{

			$message[] = '<p class="error">Please choose how your player bats.</p>';
			$error = true;

		}

		if(isset($_POST['throws']) && $_POST['throws'] != '') {

			$throws = filter_var($_POST['throws'], FILTER_SANITIZE_STRING);

		}else{

			$message[] = '<p class="error">Please choose how your player throws.</p>';
			$error = true;

		}

		// calculate player height, default to 0 on empty
		$feet = 0;
		$inches = 0;
		if(isset($_POST['feet']) && $_POST['feet'] != '') {

			$opts = array('min_range' => 3, 'max_range' => 7);
			if(filter_var($_POST['feet'], FILTER_VALIDATE_INT, $opts)) {
			
				$feet = filter_var($_POST['feet'], FILTER_SANITIZE_NUMBER_INT);

			}else{

				$message[] = '<p class="error">Feet must be between 3 &amp; 7.</p>';
				$error = true;

			}

		}

		if(isset($_POST['inches']) && $_POST['inches'] != '') {

			$opts = array('min_range' => 0, 'max_range' => 11);
			if(filter_var($_POST['inches'], FILTER_VALIDATE_INT, $opts)) {

				$inches = filter_var($_POST['inches'], FILTER_SANITIZE_NUMBER_INT);

			}else{

				$message[] = '<p class="error">Inches must be between 0 &amp; 11.</p>';
				$error = true;

			}

		}

		$height = ($feet * 12) + $inches;

		if(isset($_POST['weight']) && $_POST['weight'] != '') {

			$opts = array('min_range' => 0, 'max_range' => 400);
			if(filter_var($_POST['weight'], FILTER_VALIDATE_INT, $opts)) {			

				$weight = filter_var($_POST['weight'], FILTER_SANITIZE_NUMBER_INT);

			}else{

				$message[] = '<p class="error">Weight must be between 0 &amp; 11.</p>';
				$error = true;

			}

		}else{

			$weight = 0;			

		}

		if(isset($_POST['dob']) && $_POST['dob'] != '') {

			$dob = date('Y-m-d', strtotime($_POST['dob']));			

		}else{

			$dob = '0000-00-00';

		}

		if(isset($_POST['team']) && $_POST['team'] != '') {

			$opts = array('min_range' => 1);
			if(filter_var($_POST['team'], FILTER_VALIDATE_INT, $opts)) {

				$team = filter_var($_POST['team'], FILTER_SANITIZE_NUMBER_INT);
			
			}else{

				$message[] = '<p class="error">Please choose a team from the list.</p>';
				$error = true;

			}

		}else{

			$message[] = '<p class="error">Please choose a team for your player.</p>';
			$error = true;

		}

		if(isset($_POST['roster']) && $_POST['roster'] != '') {

			$opts = array('min_range' => 1);
			if(filter_var($_POST['roster'], FILTER_VALIDATE_INT, $opts)) {

				$roster = filter_var($_POST['roster'], FILTER_SANITIZE_NUMBER_INT);			

			}else{			

				$message[] = '<p class="error">Please choose a roster from the list.</p>';
				$error = true;			

			}

		}else{

			$roster = 0;

		}

		// handle player image upload if no other form errors
		if(isset($_FILES['player_image']) && $_FILES['player_image']['error'] != 4 && $error == false) {

			$uploaddir = 'player_images/';
			$uploadfile = $uploaddir . $user_id . '_' . basename($_FILES['player_image']['name']);															

			// check for correct file type
			if(($_FILES['player_image']['type'] == "image/gif") || ($_FILES['player_image']['type'] == "image/jpg") || ($_FILES['player_image']['type'] == "image/jpeg") || ($_FILES['player_image']['type'] == "image/pjpeg") || ($_FILES['player_image']['type'] == "image/bmp") || ($_FILES['player_image']['type'] == "image/png")) {

				// check upload status
				switch($_FILES['player_image']['error']) {
				
					case 0: // no error, upload successful
						if(file_exists($uploadfile)) { // check for dup files

							$message[] = '<p class="error">File already exists, please upload a different one.</p>';
							$error = true;

						}else{

							move_uploaded_file($_FILES['player_image']['tmp_name'], $uploadfile);
							$player_image = $user_id . '_' . basename($_FILES['player_image']['name']);	
							$message[] = '<p class="success">Player image uploaded successfully.</p>';

						}		
						break; 

					case 1: // exceeds php.ini file size
						$message[] = '<p class="error">File size too large. Please resize and upload again.</p>';
						$error = true;
						unset($uploadfile);
						break;

					case 2: // exceeds form file size
						$message[] = '<p class="error">File size too large. Please resize and upload again.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 3: // partial upload
						$message[] = '<p class="error">File only partially uploaded. Please try again.</p>';
						$error = true;
						unset($uploadfile);
						break;

					case 4: // no file uploaded
						$message[] = '<p class="error">No file uploaded.</p>';
						$error = true;
						unset($uploadfile);
						break;

					case 6: // missing temp folder
						$message[] = '<p class="error">Upload failed. Try again later.</p>';
						$message[] = '<p class="notice">Missing temp folder.</p>';
						$error = true;
						unset($uploadfile);
						break;						

					case 7: // failed to write to disk
						$message[] = '<p class="error">Upload failed. Try again later.</p>';
						$message[] = '<p class="notice">Failed to write to disk.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 8: // extension caused failure
						$message[] = '<p class="error">Upload failed. Try again later.</p>';
						$message[] = '<p class="notice">Extension caused failure.</p>';
						$error = true;
						unset($uploadfile);
						break;				

				}
				
			}else{ // incorrect type

				$message[] = '<p class="error">Incorrect file type, image must be a GIF, JPG, PNG or BMP.</p>';
				$error = true;
				unset($uploadfile);

			} 

		}else{ // no player_image

			$player_image = '';

		}

		if($error == false) {

			// prep insert query
			$sql = "INSERT INTO players (team_id, user_id, name, number, position, bats, throws, height, weight, dob, player_img) ";
			$sql .= "VALUES ('" . $team . "', '" . $user_id . "', '" . $name . "', '" . $number . "', '" . $position . "', '";
			$sql .= $bats . "', '" . $throws . "', '" . $height . "', '" . $weight . "', '" . $dob . "', '" . $player_image . "')";

			if($db->exec($sql) == 1) {

				// get id of player
				$id = $db->lastInsertId();

				// if roster was chosen, add player to it
				$sql = "INSERT INTO player_stats (player_id) VALUES ('" . $id . "')";
				$db->exec($sql);

				if(isset($roster) && $roster > 0) {

					$sql = "INSERT INTO rosters_players (roster_id, player_id) VALUES ('" . $roster . "', '" . $id . "')";

					if($db->exec($sql) == 1) {

						$message[] = '<p class="success">Player successfully added to chosen roster.</p>';

					}else{

						$message[] = '<p class="error">Could not add player to chosen roster.</p>';
						$error = true;

					}

				}

				$message[] = '<p class="success">Player created successfully.</p>';

			}else{

				$message[] = '<p class="error">Could not create player.</p>';
				$message[] = '<p class="notice">' . print_r($db->errorInfo()) . '</p>';
				$error = true;

			}

		}

		if($_POST['createPlayer'] == 1) { // ajax request

			if(isset($message)) foreach($message as $m) $response .= $m;
			exit($response);

		}

	}
	
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Create a Player</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css"><link rel="stylesheet" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
    	<h1>Create a Player</h1>
        <p>Use the form below to create a new player.</p>
        <form action="" method="post" id="createPlayer" enctype="multipart/form-data">
        	<fieldset>
            	<legend>Player Details</legend>
                <?php if(isset($message)) foreach($message as $m) print $m; ?>
                <p><label for="first_name">First Name:</label><input type="text" name="first_name" id="first_name" required /></p>
                <p><label for="last_name">Last Name:</label><input type="text" name="last_name" id="last_name" required /></p>
                <p><label for="number">Number:</label><input type="number" name="number" id="number" min="0" max="99" step="1" required /></p>
                <p>
                	<label for="position">Position:</label>
                    <select name="position" id="position" required>
                    	<?php

							foreach($db->query("SELECT position_id, title FROM positions") as $p) {

								print '<option value="' . $p[0] . '">' . $p[1] . '</option>';

							}

						?>
                    </select>
                </p>
                <p><label>Bats:</label></p>
                <p class="radio"><input type="radio" name="bats" id="bats_l" value="L" /><label for="bats_l">Left</label></p>
                <p class="radio"><input type="radio" name="bats" id="bats_r" value="R" /><label for="bats_r">Right</label></p>
                <p class="radio"><input type="radio" name="bats" id="bats_s" value="S" /><label for="bats_s">Switch</label></p>
                <p><label>Throws:</label></p>
                <p class="radio"><input type="radio" name="throws" id="throws_l" value="L" /><label for="throws_l">Left</label></p>
                <p class="radio"><input type="radio" name="throws" id="throws_r" value="R" /><label for="throws_r">Right</label></p>
                <p><label for="feet">Height:</label><input type="number" min="3" max="7" step="1" name="feet" id="feet" />' - <input type="number" min="0" max="11" step="1" name="inches" id="inches" />"</p>
                <p><label for="weight">Weight:</label><input type="number" min="0" max="400" step="1" name="weight" id="weight" />lbs.</p>
                <p><label for="dob">Date of Birth:</label><input type="date" name="dob" id="dob" placeholder="MM-DD-YYYY" /></p>
                <input type="hidden" name="MAX_FILE_SIZE" value="900000" />
                <p><label for="player_image">Player Image:</label><input type="file" name="player_image" id="player_image" /></p>
                <p>
                	<!-- choosing the last option triggers a modal window 
                    in which to create a new team via an ajax request -->
                	<label for="team">Team:</label>
                	<select name="team" id="team" required>
                    	<option value="0">Choose One</option>
                    	<?php

							foreach($db->query("SELECT team_id, city, name FROM teams WHERE user_id IN (0, " . $user_id . ")") as $t) {

								print '<option value="' . $t['team_id'] . '">' . $t['city'] . ' ' . $t['name'] . '</option>';

							}

						?>
                    	<option value="">Create a New Team</option>
                    </select>    
                </p>
                <p>
                	<!-- choosing last option creates a new roster -->
                    <label for="roster">Roster:</label>
                    <select name="roster" id="roster" disabled>
                    	<option value="0">Choose One</option>
                    	<?php

							$sql = "SELECT roster_id, nickname FROM rosters WHERE user_id = " . $user_id;
							foreach($db->query($sql) as $r) {

								print '<option value="' . $r['roster_id'] . '">' . $r['nickname'] . '</option>';

							}
						
						?>
                        <option value="">Create a New Roster</option>
                    </select>
                </p>
                <input type="submit" name="create_player" id="create_player" value="Create Player" />
            </fieldset>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
    <script>
    	$(document).ready(function() {	
			// check for native date picker, default to jQuery UI if not
			if(!Modernizr.inputtypes.date) {
				$( "#dob" ).datepicker({
					changeMonth: true,
					changeYear: true,
					dateFormat: 'mm/dd/yy',
					yearRange: '1900:2011'
				});
			}

			// TODO: make this work with file uploads		
			$("#team").change(function() { // listen for change on team input
				// enable roster selector based on team value
				if($("#team").val() != '') { 
					$("#roster").attr("disabled", "");
				}
				// show new team form
				if($("#team").val() == '') {
					$("#dialogTeam").dialog("open");
				}
			});

			$("#roster").change(function() { // listen for change on roster input
				// show roster form
				if($("#roster").val() == '') {
					$("#dialogRoster").dialog("open");
				}
			});

			// new team dialog
			$("#dialogTeam").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {

					"Create Team": function() {
						$.post(
							"create-team.php",
							{
								team_city: $("#team_city").val(),
								team_name: $("#team_name").val(),
								division: $("#division").val(),
								league: $("#league").val(),
								url: $("#url").val(),
								createTeam: $("#createTeam").val()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialogTeam").prepend(data);
								if($(data).hasClass('success')) {
									// set value of team select input
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$("#team").append('<option value="' + select_id + '" selected>' + select_title + '</option>');

									// enable roster select
									$("#roster").attr("disabled", "");

									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialogTeam").dialog("close"); }, 2500);
								}
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});

			// new roster dialog
			$("#dialogRoster").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {
					"Create Roster": function() {
						$.post(
							"create-roster.php",
							{
								team_id: $("#team").val(),
								nickname: $("#nickname").val(),
								createRoster: $("#createRoster").val()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialogRoster").prepend(data);
								if($(data).hasClass('success')) {
									// set value of roster select input
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$("#roster").append('<option value="' + select_id + '" selected>' + select_title + '</option>');
									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialogRoster").dialog("close"); }, 2500);
								}								
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});
		});
    </script>
    <fieldset id="dialogTeam" title="Create a New Team">
    	<p><label for="team_city">Team City:</label><input type="text" name="team_city" id="team_city" required /></p>
        <p><label for="team_name">Team Name:</label><input type="text" name="team_name" id="team_name" required /></p>
        <p>
            <label for="division">Division:</label>
            <select name="division" id="division">
                <?php                

                    $sql = "SHOW COLUMNS FROM teams LIKE 'division'";
                    $divs = $db->query($sql)->fetchAll();
                    $div = $divs[0]['Type'];                                                
                    $regex = "/'(.*?)'/";

                    preg_match_all($regex, $div, $enum_array);
                    $enum_fields = $enum_array[1];

                    foreach($enum_fields as $type) print '<option value="' . $type . '">' . $type . '</option>';                    
                ?>
            </select>    
        </p>
        <p>
            <label for="league">League:</label>
            <select name="league" id="league">
                <?php

                    $sql = "SHOW COLUMNS FROM teams LIKE 'league'";
                    $divs = $db->query($sql)->fetchAll();
                    $div = $divs[0]['Type'];
                    $regex = "/'(.*?)'/";

                    preg_match_all($regex, $div, $enum_array);
                    $enum_fields = $enum_array[1];                    

                    foreach($enum_fields as $type) print '<option value="' . $type . '">' . $type . '</option>';                

                ?>
            </select>
        </p>
        <p><label for="url">Team URL:</label><input type="url" name="url" id="url" placeholder="http://www.example.com" /></p>
        <input type="hidden" name="createTeam" value="1" id="createTeam" />
    </fieldset>
    <fieldset id="dialogRoster" title="Create a New Roster">
        <input type="hidden" name="createRoster" id="createRoster" value="1" />
        <p><label for="nickname">Roster Nickname:</label><input type="text" name="nickname" id="nickname" required /></p>
    </fieldset>
</body>
</html>